<template>
  <div class="box">
    <div class="startExam">
      <div class="aside">
        <div class="viewBox">
          <div class="question" v-for="(item,index) in questionsList?.list" :key="index" :ref="questionRefs[index]">
            <div class="viewTitle"  :class="[{ errorQuestion: getAnswer(item) != getStudentAnswer(item) }]" >{{ index+1 }}、{{ item.questionTitle}}<span class="titleScore">({{ item.score }}分)</span></div>
            <div class="questionBox">
              <!-- 单选 -->
              <template v-if="item.questionType==0">
                <el-radio-group v-model="item.studentAnswer" :disabled="data.examEnd">
                  <div
                    v-for="(option,ins) in item.options" 
                    :key="ins" 
                    class="form-item-with-radio"
                  >
                    <el-radio  :label="option.id" :value="`${option.id}`">{{keyMap[ins]}}. &nbsp;{{option.optionText}}</el-radio>
                  </div>
                </el-radio-group>
              </template>

              <!-- 多选 -->
              <template v-if="item.questionType==1">
                <el-checkbox-group v-model="item.studentAnswer"  :disabled="data.examEnd">
                    <div 
                      v-for="(option,ins) in item.options" 
                      :key="ins" 
                      class="form-item-with-radio"
                    >
                      <el-checkbox :label="option.id" :value="`${option.id}`">{{keyMap[ins]}}. &nbsp;{{option.optionText}}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </template>

              <!-- 判断 -->
              <template v-if="item.questionType==2">
                <el-radio-group v-model="item.studentAnswer" size="small"  :disabled="data.examEnd">
                  <el-radio-button v-for="(option,ins) in item.options" :key="ins" :label="option.id" :value="`${option.id}`" border>{{option.optionText}}</el-radio-button>
                </el-radio-group>
              </template>

              <!-- 主观题 -->
              <template v-if="item.questionType==3">
                <el-input type="textarea"  :disabled="data.examEnd" :autosize="{ minRows: 7}" placeholder="" v-model="item.studentAnswer"></el-input>
              </template>
              <div v-if="examStudent.examStatus >= 1" class="question-answer"><span class="answer">正确答案: {{ getAnswer(item) }}</span><span class="answer">考生答案: {{ getStudentAnswer(item) }}</span></div>
            </div>
          </div>
        </div>
      </div>
      <div class="main">
        <div class="question-numbers">
          <div class="countdown-timer">
            <template v-if="!examStudent.examStatus">
              <h3>考试结束倒计时</h3>
              <div class="time">{{ data.countdown }}</div>
            </template>
            <div v-else-if="examStudent.examStatus==3">
              <h2 class="score">考试成绩</h2>
              <div class="scoreBox"><h2 class="scoreData">{{ examStudent.score }}</h2><span>分</span></div>
            </div>
            <div v-else>
              <h2 class="score">试卷批改中</h2>
            </div>
          </div>
          <h3>题号</h3>
          <div class="numbers">
            <div 
              v-for="(question, index) in questionsList?.list" 
              :key="index" 
              :class="['number-button', { active: question.questionType==1?question.studentAnswer?.length:question.studentAnswer },{ error: getAnswer(question) != getStudentAnswer(question) }]" 
              @click="scrollToQuestion(index)"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>
        <div class="examBtn" style="margin: 30px 0;" v-if="questionsList?.list?.length">
          <el-button type="primary" v-if="!data.examEnd" @click="submitQuestions()">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,reactive, onMounted,onBeforeUnmount,computed, nextTick } from 'vue'
import { useRoute } from 'vue-router';
import router from '@/router'
import axios from '@/axios/index.js'
import {ElMessage,ElMessageBox,ElLoading} from 'element-plus'
import { exam } from '@/stores/exam';
const examStore = exam();

const route = useRoute();
let questionsList = ref()

let data = reactive({
  examEndTime:"00:00:00",
  countdown:"",
  examEnd:false,
});
const calculateCountdown = () => {
  const endTime = new Date(data.examEndTime.replace(/-/g, '/')).getTime(); 
  const now = Date.now();
  const remainingTime = endTime - now;

  if (remainingTime <= 0) {
    data.countdown = "考试结束";
    data.examEnd = true;
    clearInterval(interval.value);
    if(questionsList.value.status !=2){
      submitQuestions();
    }
    ElMessageBox.alert('考试时间到', '提示', {});
  } else {
    // 分别计算天、小时、分钟、秒
    const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24)); // 计算剩余的天数
    const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 剩余小时数
    const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

    // 如果天数大于 0，显示天数，否则只显示小时、分钟、秒
    if (days > 0) {
      data.countdown = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
    } else {
      data.countdown = `${hours}小时 ${minutes}分钟 ${seconds}秒`;
    }
  }
};





const interval = ref(null);
let student = ref({})
onMounted(() =>{
  student.value = JSON.parse(localStorage.getItem('student'));
  console.log(student.value,student.value?.studentInfo?.studentId)
  
  loadingInstance.value = ElLoading.service({ fullscreen: true })

  window.addEventListener('beforeunload', handleBeforeUnload)
  interval.value = setInterval(calculateCountdown, 1000);
});

onBeforeUnmount(() => {
  clearInterval(interval.value);
});

const keyMap = {
  0:"A",
  1:"B",
  2:"C",
  3:"D",
}
const loadingInstance = ref();

//获取正确答案
const getAnswer = (item) =>{
  let data = []
  if(examStudent.value.examStatus >= 1){
    if(item.questionType ==2){
      item.options.forEach((option,index) =>{
        if(option.isCorrect){
          data = option.optionText
        }
      })
      return data
    }else if(item.questionType ==3){
      data = item.studentAnswer + " "
      return data
    }else{
      item.options.forEach((option,index) =>{
        
        if(option.isCorrect){
            data.push(keyMap[index])
        }
      })
      return data.join(",")
    }
  }
}
//获取考生答案
const getStudentAnswer = (item) =>{
  let data = []
  if(examStudent.value.examStatus >= 1){
    let studentData = item.questionType == 0 ||item.questionType == 1 ||item.questionType == 3?item.studentAnswer:item.studentAnswer.split(",")
    if(item.questionType != 3 && item.questionType != 2){
      item.options.forEach((option,index) =>{
        if(studentData.includes(`${option.id}`)){
          data.push(keyMap[index])
        }
      })
      return data.join(",")
    }else{
      if(item.questionType ==2){
        item.options.forEach((option,index) =>{
          if(option.id==item.studentAnswer){
            data = option.optionText
          }
        })
        return data
      }else{
        return item.studentAnswer
      }
    }
  }
}
let examStudent = ref({examStatus:0})
const getExamStudent = async() =>{
  try {
    const res = await axios.get("/examStudent/getOne",{
        params:{
          studentId:student.value?.studentInfo?.studentId,
          examId:route.query.id,
      }
    })
    if(res.data.code==200 && res.data.data){
      examStudent.value = res.data.data
      console.log(examStudent.value);
    }
  } catch (error) {
    console.log(error);
  }
}
const getQuestionsList = async() =>{
  try {
    const res = await axios.get("/exam/getExam",{
        params:{
        recordsId:route.query.id
      }
    })
    if(res.data.code==200){
      questionsList.value = res.data.data
      examStore.setExamInformation(res.data.data)
      setTimeout(() =>{

        data.examEndTime = res.data.data.examEndTime
          questionsList.value.list.forEach((item) =>{
            if(item.questionType==1){
              if(examStudent.value.examStatus >= 1){
                item.studentAnswer = item.studentAnswer.split(",")
              }else{
                item.studentAnswer = []
              }
            }
          })
        //已提交考试
        if(examStudent.value.examStatus >= 1){
          console.log("jin")
          data.countdown = "已答题完毕";
          clearInterval(interval.value);
          data.examEnd = true;
        }
        questionRefs.value = questionsList.value.list.map(() => ref(null))
        loadingInstance.value.close()
      },1000)
    }
  } catch (error) {
    console.log(error);
  }
}
getExamStudent()

getQuestionsList()


const submitQuestions = () =>{
  loadingInstance.value = ElLoading.service({ fullscreen: true })
  let list = []
  let count = 0;
  questionsList.value.list.forEach(item => {
    console.log(item);
    
    let data = {
      "studentId":student.value?.studentInfo?.studentId+"",
      "examRecordId":item.examRecordId,
      "questionId":item.id,
      "score":item.score,
      "createBy":item.createBy,
      studentAnswer:"",
    }
    if(item.studentAnswer ||item.studentAnswer==0){
      if(item.questionType == 0 ||item.questionType == 2 ||item.questionType == 3){//单选、判断、主观
        data.studentAnswer=item.studentAnswer
        if(item.questionType == 0 ||item.questionType == 2){
          // 查找 studentAnswer 对应的索引
          const studentAnswerId = item.studentAnswer;
          const optionIndex = item.options.findIndex(option => option.id == studentAnswerId);

          // 根据索引从 keyMap 中获取对应的字母
          if (optionIndex !== -1) {
            data.studentOption = keyMap[optionIndex];
          } else {
            console.log("未找到对应的选项");
          }
        }else{
          data.studentOption = item.studentAnswer
        }
      }else if(item.questionType == 1){//多选
        data.studentAnswer = item.studentAnswer.join(",")
        let mappedAnswers = item.studentAnswer.map(studentAnswerId => {
            // 找到该 studentAnswerId 在 options 中的索引
            const optionIndex = item.options.findIndex(option => option.id == studentAnswerId);

            // 根据索引从 keyMap 中获取对应的字母
            if (optionIndex !== -1) {
              return keyMap[optionIndex];
            }
            return null; // 如果没找到对应的索引，返回 null（可以根据需求进行处理）
          }).filter(Boolean); // 过滤掉 null 值

          // 将字母用逗号拼接成一个字符串
          data.studentOption = mappedAnswers.join(",");
          console.log(data.studentOption);
      }
      count++;
    }
    list.push(data)

  });
  if(count<questionsList.value.list.length && !data.examEnd){//有题目未做答
    ElMessageBox.confirm(
      '有题目未做答,是否确认提交',
      '提示',
      {
        type: 'warning',
      }
    )
      .then(() => {
        console.log("提交的数据",list);
        setExamGrades(list)
        data.countdown = "已提交";
        clearInterval(interval.value);
        data.examEnd = true;
      })
      .catch(() => {
        loadingInstance.value.close()
      })
  }else{
    console.log("提交的数据",list);
    setExamGrades(list)
    data.countdown = "已提交";
    clearInterval(interval.value);
    data.examEnd = true;
  }

}


const setExamGrades = async(data) =>{
  try {
    const res = await axios.post("/grades/batchAdd",data,{ headers: { 'content-type': 'application/json' } })
    console.log(res);
    loadingInstance.value.close()
    if(res.data.code==200){
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
      examStudent.value =res.data.data
    }
  } catch (error) {
    console.log(error);
  }
}
// 页面刷新提示
onBeforeUnmount(() =>{
  window.removeEventListener('beforeunload', handleBeforeUnload);
})
const handleBeforeUnload = (event) => {
  const message = '您确定要离开此页面吗？';
  event.returnValue = message; 
  return message; 
}

// 点击题号滑动到某一题
const questionRefs = ref([]);
const scrollToQuestion = (index) => {
  const questionElement = questionRefs.value[index].value;
  if (questionElement) {
    questionElement[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

</script>

<style scoped lang="less">
*{
  font-size: 16px;
}
.box{
  width: 100%;
  padding: 50px;
  .startExam{
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .aside{
    width: 68%;
    border: 2px solid #e3e3e3;
    height: 100%;
  }
  .main{
    width: 30%;
    border: 2px solid #e3e3e3;
    height: 100%;
  }
}
.aside{
    overflow-y: scroll;
    height: 100%;
    width: 70%;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .viewBox{
      padding: 10px 40px;
      overflow-y: scroll;
      height: calc(100vh - 200px);
      .h3{
        display: flex;
        align-items: center;
      }
      .viewTitle{
        margin: 20px;
        ::v-deep el-radio{
          margin-right: 10px;
        }
        .titleScore{
          margin-left:10px;
        }
      }
      .errorQuestion{
        color: #F56C6C;
        display: inline-block;
      }
      .viewBox-item{
        margin:10px 0;
        display: flex;
        >div{
          // margin-left: 20px;
          width: 100%;
          font-size: 14px;
        }
      }
    }
    
  }
.main{
    height: 100%;
    width: 27%;
    border: 1px solid #ccc;
    padding: 10px 40px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .numbers {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .number-button {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: #eee;
      color: #000;
    }

    .number-button.active {
      background-color: #007bff;
      color: #fff;
    }

    .number-button.error {
      background-color: #F56C6C;
      color: #fff;
    }
    .countdown-timer {
      text-align: center;
      margin-bottom: 20px;
      .score{
        font-size: 30px;
        margin: 0;
        color: red;
      }
      .scoreBox{
        display: flex;
        justify-content: center;
        >span{
          display: flex;
          align-items: center;
          margin-top: 20px;
          margin-left: 5px;
        }
        
      }
      .scoreData{
        font-size: 50px;
        color: red;
        margin: 10px 0;
        font-weight: bold;
      }
    }

    .time {
      font-size: 2em;
      font-weight: bold;
    }
  }
  .examBtn{
    display: flex;
    justify-content: end;
    margin: 40px;
  }
  ::v-deep .el-button.is-circle {
    width: 20px;
    height: 20px;
  }
  .form-item-with-radio{
    display: flex;
    width: 100%;
    box-sizing: border-box;
    align-items: center;
    .el-checkbox{
      margin-right: 32px;
    }
  }
  .question{
    .questionBox{
      margin-left: 50px;
      .question-answer{
        margin-top: 20px;
        text-decoration: solid;
        .answer{
          margin-right: 20px;
          background: #EBEDF0;
        }
      }
    }
  }

  .numbers {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .number-button {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: #eee;
      color: #000;
    }

    .number-button.active {
      background-color: #007bff;
      color: #fff;
    }

    
</style>